#!usr/bin/python

# -*- coding: utf-8 -*-


from PyQt4 import QtCore,QtGui

from model import integration_peaks
from gui import integr_gui
from core import processing as proc, pySpec as obj
from parsers import lxml_target
import os.path as path
from controller import ControllerDialog as dial

class integration_controller(:
	"""Class controller, (calls a class for peak_picking and alignment)"""
	
	def __init__(self,lspl, win):
		"""Constructor like all models"""
		dial.__init__(self, lspl, widget)
				
		#connection
		QtCore.QObject.connect( self.widget.pushButton, QtCore.SIGNAL ( "clicked () " ), self.printing)
		QtCore.QObject.connect( self.widget.buttonBox, QtCore.SIGNAL ( "accepted() " ), self.integrate)
		#QtCore.QObject.connect( self.widget.centWave, QtCore.SIGNAL ( "toggled(bool)" ), self.changes_centwave)
		#QtCore.QObject.connect( self.widget.matchedfiltered, QtCore.SIGNAL ( "toggled(bool)" ), self.changes_matchedfiltered)
		QtCore.QObject.connect( self.widget.merging, QtCore.SIGNAL ( "toggled(bool)" ), self.changes_merge)
	
	
	
	def changes_merge(self, boolean):
		if not boolean:
			self.widget.lineEdit_10.setEnabled(False)
			self.widget.lineEdit_11.setEnabled(False)
		if boolean:
			self.widget.lineEdit_10.setEnabled(True)
			self.widget.lineEdit_11.setEnabled(True)
			
	def changes_centwave(self, boolean):
		if boolean:
			self.widget.enable_disable_matchedfiltered(not boolean)
			self.widget.enable_disable_centwave(boolean)
			
	def changes_matchedfiltered(self, boolean):
		if boolean:
			self.widget.enable_disable_centwave(not boolean)
			self.widget.enable_disable_matchedfiltered(boolean)
		
	def printing(self):
		"""just print already parsed files"""
		self.widget.printing(self.lspl)

	def integrate (self) :
		"""Main Function """
		
		#parameters of integration
		filename_to_process = self.widget.lineEdit.text().split(';')
		
		fwhm = float(self.widget.lineEdit_3.text())
		step = float(self.widget.lineEdit_4.text())
		steps = float(self.widget.lineEdit_5.text())
		mzdiff = float(self.widget.lineEdit_6.text())
		snthresh = float(self.widget.lineEdit_7.text())
		max = int(self.widget.lineEdit_2.text())
		plot =self.widget.plot.isChecked()
		
		if self.widget.radioButton.isChecked():
			align = "loess"
		elif self.widget.radioButton_2.isChecked():
			align ="obiwarp"
		else:
			align =None
			
		merging = self.widget.merging.isChecked()
		files_to_merge =None
		name = None
		if merging:
			files_to_merge = self.widget.lineEdit_10.text().split(';')
			name = str(self.widget.lineEdit_11.text())

		self.widget.close()
		
		lspl = obj.ListSample()
		for xml in filename_to_process:
			if xml not in self.lspl.getFiles():
				print ("error, must parse before")
				return
			lspl.append(self.lspl.Sample(xml))
		
		spl =None
		if merging:
			spl =obj.Sample(name)
		
		thread = Integration_thread(lspl, self.lspl, self.widget.parent.peak_model, fwhm, step, steps, mzdiff, snthresh, max, plot, align,\
					files_to_merge, spl, self.widget.parent)
		QtCore.QObject.connect(thread, QtCore.SIGNAL("sent_model"),self.update_treeView_2)
		QtCore.QObject.connect(thread, QtCore.SIGNAL("status_message"),self.widget.parent.ShowInStatusBar)
		QtCore.QObject.connect(thread, QtCore.SIGNAL("started()"),self.widget.parent.to_indetermined_mode)
		QtCore.QObject.connect(thread, QtCore.SIGNAL("finished()"),self.widget.parent.to_determined_mode)
		thread.begin()
		
		
	def update_treeView_2 (self, model):
		self.widget.parent.treeView_2.setModel(model)



class Integration_thread(QtCore.QThread):
	"""integration thread progress in indeterminate mode"""
	
	
	def __init__(self, lspl, true_lspl, model, fwhm, step, steps, mzdiff, snthresh, max, plot, align, files_to_merge, spl,  parent = None):
		QtCore.QThread.__init__(self, parent)
		self.lspl =lspl
		self.model = model
		self.fwhm =fwhm
		self.step =step
		self.steps= steps
		self.mzdiff =mzdiff
		self.snthresh =snthresh
		self.max = max
		self.plot =plot
		self.align =align
		self.files_to_merge = files_to_merge
		self.spl =spl
		self.true_lspl =true_lspl
		
	def run(self):
		
		integr = integration_peaks.integration_by_xcms (self.lspl)
		integr.transformation()
		self.emit(QtCore.SIGNAL("status_message"), "Integration...")
		integr.integrate_align(self.fwhm, self.step, self.steps, self.mzdiff, self.snthresh, self.max, self.plot, self.align)
		self.emit(QtCore.SIGNAL("status_message"), "Getting peaks from xcms...")
		proc.creating_peakList(self.lspl)
		self.emit(QtCore.SIGNAL("status_message"), "Merging...")
		"""
		Move to the model
		"""
		if self.spl:
			self.true_lspl.append(integr.make_new_sample(self.spl, self.files_to_merge))
			
			for filename in self.files_to_merge:
				try:
					self.true_lspl.Remove(filename)
				except ValueError:pass
				
				for i in xrange(self.parent().chrom_model.rowCount()):
					index = self.parent().chrom_model.index(i, 0)
					if self.parent().chrom_model.data(index, QtCore.Qt.DisplayRole).toString() == filename:
						self.parent().chrom_model.removeRow(index.row())
						self.parent().spectr_model.removeRow(index.row())
						#update the view
						self.parent().treeView.rowsRemoved(index, index.row(), index.row())
		
			root_chrom = QtGui.QStandardItem(QtGui.QIcon(QtGui.QPixmap(path.normcase("gui/icons/grid.png"))), self.spl.getXmlFile())
			root_chrom.setEditable(False)
			for chrom in self.spl.getChromatogram():
				std_item = QtGui.QStandardItem(QtGui.QIcon(QtGui.QPixmap(path.normcase("gui/icons/pickedpeakicon.png"))))
				std_item.setEditable(False)
				root_chrom.appendRow(std_item, str(chrom.get_trans()))
			self.parent().chrom_model.appendRow(root_chrom)
			
			root_spectr = QtGui.QStandardItem(QtGui.QIcon(QtGui.QPixmap(path.normcase("gui/icons/grid.png"))), self.spl.getXmlFile())
			for spectr in self.spl.getSpectra():
				std_item = QtGui.QStandardItem(QtGui.QIcon(QtGui.QPixmap(path.normcase("gui/icons/pickedpeakicon.png"))))
				std_item.setEditable(False)
				root_spectr.appendRow(std_item, str(spectr.t_min))
			self.parent().spectr_model.appendRow(root_spectr)

		
		for spl in self.true_lspl:
			root = QtGui.QStandardItem(QtGui.QIcon(QtGui.QPixmap(path.normcase("gui/icons/grid.png"))), spl.getXmlFile())
			root.setEditable(False)
			for peak in spl.get_peak_list():
				std_item = QtGui.QStandardItem(QtGui.QIcon(QtGui.QPixmap(path.normcase("gui\\icons\\pickedpeakicon.png"))), \
							str(peak.get_trans_prec())+" "+ str(peak.get_rt()) )
				std_item.setEditable(False)
				root.appendRow(std_item)#, str(peak.get_trans_prec())+" "+ str(peak.get_rt()))
			self.model.appendRow(root)
		self.emit(QtCore.SIGNAL("sent_model"), self.model)
		
	def begin(self):
		self.start()
		self.exec_()
					   
